#!/bin/bash

#exit code instruction
# code 10 : not run as root
# code 11 : neither curl or wget available
# code 12 : repo not given
# code 13 : import_key not given
# code 14 : all repo of proxy not reachable
# code 15 : download install package fail
# code 16 : unpack package fail
# code 17 : Agent still running and cannot be uninstalled
# code 18 : Proxy still running and cannot be uninstalled

export LC_ALL=C
logFile=/tmp/installAgent.log
out(){
    echo `date "+%Y-%m-%d %H:%M:%S"`": $*"
    echo `date "+%Y-%m-%d %H:%M:%S"`": $*" >> $logFile
}

out "Agent install script started!"

validateRunAsRoot()
{
  if [[ $EUID -ne 0 ]]; then
      out "ERROR: 需要以root身份运行，请切换到root运行！"
      exit 10
  fi
  out "RunAs user check passed! current user is root"
}



logFilePath="/var/log/Agent-install.log"
import_key=${import_key}
repo=${repo}
download_prefix=${download_prefix}

db_host=${db_host}
db_port=${db_port}
db_user=${db_user}
db_pwd=${db_pwd}
db_name=${db_name}
devicd_list=${devicd_list}

issudo=${issudo}
sudo_passwd_base64=${sudo_passwd}



if [ "x$import_key" == "x" ]; then
    import_key=$1
    repo=$2
    download_prefix=$3
    issudo=$4
    sudo_passwd_base64=$5

    # db_host=$6
    # db_port=$7
    # db_user=$8
    # db_pwd=$9
    # db_name=$10
    # devicd_list=$11
fi

if [ "$issudo" == "issudo" ]; then
    if [ -n "$sudo_passwd_base64" ] ; then
        sudo_passwd=$(echo "$sudo_passwd_base64" | base64 -d )
        echo "$sudo_passwd" | sudo -S /bin/bash $0 $import_key $repo  $download_prefix
        exit $?
    else
        sudo /bin/bash $0 $import_key $repo $download_prefix
        exit $?
    fi
fi

validateRunAsRoot

validateToolInstalled()
{
  toolName=$1
  $toolName --help >/dev/null 2>&1
  if [[ $? -eq 0 ]]; then
      return 0
  else
      return 1
  fi
}

usage()
{
  echo Usage:
  out "export import_key=xxxxxxx;bash installAgent.sh "
}

validateInputParameters()
{
  if [ "x${import_key}" == "x"  ];then
     echo ERROR: import_key is required, current not provided
     usage
     exit 1
  fi
}


exitIfImported()
{
  if [ -f "$installPath/conf/setting.py" ];then
      out "Agent already installed!!!"
      out "Please execute '/usr/bin/uninstallAgent.sh' to uninstall it then run this script again."
      exit 18
  fi
}


# return 64 or 32
getArchBit()
{
    sys_arch=`uname -m`
    sys_arch=${sys_arch:0-2:2}
    if [ "$sys_arch" == "64" ];then
        echo "64"
    else
        echo "32"
    fi
}


getOsRelease()
{
    issue=$(cat /etc/issue)
    line=$(echo $issue |grep "CentOS" |wc -l)
    if [[ $line -eq 1 ]]; then
        echo "CentOS"
        return
    fi
    line=$(echo $issue |grep "SUSE Linux Enterprise Server" |wc -l)
    if [[ $line -eq 1 ]]; then
        echo "SLES"
        return
    fi
    line=$(echo $issue |grep "openSUSE" |wc -l)
    if [[ $line -eq 1 ]]; then
        echo "openSUSE"
        return
    fi
    line=$(echo $issue |grep "Debian" |wc -l)
    if [[ $line -eq 1 ]]; then
        echo "Debian"
        return
    fi
    line=$(echo $issue |grep "Ubuntu" |wc -l)
    if [[ $line -eq 1 ]]; then
        echo "Ubuntu"
        return
    fi
}

archBit=$(getArchBit)
AgentDownloadURL="$download_prefix/downloads/Agent/Agent-linux$archBit-latest.tar.gz"
downloadDirPath=/tmp/Agent
downloadedPath="$downloadDirPath/Agent-linux$archBit-latest.tar.gz"
installPath="/usr/local/Agent"
osRelease=$(getOsRelease)

depPkgs=()
#pkgs to be installed
case "$osRelease" in
    'Debian')
        depPkgs=("libxrender1")
        ;;
    'CentOS')
        depPkgs=("libXrender")
        ;;
    'Ubuntu')
        ;;
    'openSUSE' | 'SLES')
        ;;
    *)
        ;;
esac

checkAndInstallDepPkgs()
{
    for pkg in $depPkgs
    do
        case "$osRelease" in
            'CentOS')
                rpm -qa |grep $pkg >/dev/null 2>&1
                if [[ $? -ne 0 ]]; then
                    echo "Installing $pkg"
                    yum install -y "$pkg"
                fi
                ;;
            'Debian' | 'Ubuntu')
                dpkg -s $pkg >/dev/null 2>&1
                if [[ $? -ne 0 ]]; then
                    echo "Installing $pkg"
                    apt-get install -y "$pkg"
                fi
                ;;
            'openSUSE' | 'SLES')
                rpm -qa |grep $pkg >/dev/null 2>&1
                if [[ $? -ne 0 ]]; then
                    echo "Installing $pkg"
                    zypper in -y "$pkg"
                fi
                ;;
            *)
                echo "You can manually install missing package if Agent not run properly"
                ;;
        esac
    done
}


downloadGateway()
{
    out "start to install Agent..."
    if [ -f "$installPath/conf/setting.py" ];then
        out "Agent is already running, if want to reinstall, please first uninstall Agent"
        exit 0
    fi

    echo "AgentDownloadURL=$agentInstallScriptDownloadURL"  >> $logFilePath
    out "download url is $AgentDownloadURL"  >> $logFilePath
    out "downloading from $AgentDownloadURL"
    rm -rf $downloadedPath
    mkdir -p $downloadDirPath
    validateToolInstalled wget
    if [ $? == 0 ];then
        out "download cmd is wget -O $downloadedPath --tries=2 --timeout=60 --wait=3 $AgentDownloadURL 2>&1 >> $logFilePath"  >> $logFilePath
        wget -O $downloadedPath --tries=2 --timeout=60 --wait=3 --no-check-certificate $AgentDownloadURL
        if [ $? -ne 0 ];then
            out "ERROR: Agent download failed"
            exit 15
        fi
    else
        validateToolInstalled curl
        if [ $? -ne 0 ];then
            out "ERROR: both wget and curl are missing, please first install one of them manually then try again!"
            exit 18
        fi
        out ": download cmd is curl -L -o $downloadedPath --retry 2 --retry-delay 3 --connect-timeout 60 $AgentDownloadURL 2>&1 >> $logFilePath"  >> $logFilePath
        curl -L -o $downloadedPath --retry 2 --retry-delay 3 -k --connect-timeout 60 $AgentDownloadURL
        if [ $? -ne 0 ];then
            out "ERROR: Agent download failed"
            exit 15
        fi
    fi
    if [ -f $downloadedPath ];then
        out "Agent package downloaded to $downloadedPath"
    else
        out "ERROR: Agent download failed，$downloadedPath not exist!"
        exit 1
    fi
}

installAgent()
{

    if [ -d $installPath ];then
	    out "path $installPath exists, will be overwritten."
	fi
	out "unpack $downloadedPath to $installPath"
    tar -zxf $downloadedPath -C /usr/local/
    if [ $? == 0 ];then
        out "unpack done!"
    else
        out  "unpack fail!"
        exit 1
    fi
    chown -R root:root $installPath
    chmod -R o-rwx $installPath
    chmod -R  u+x $installPath


    rm -f /usr/bin/uninstallAgent.sh >/dev/null 2>&1
    rm -f /usr/bin/startAgent.sh >/dev/null 2>&1
    rm -f /usr/bin/stopAgent.sh >/dev/null 2>&1

    ln -s $installPath/bin/uninstallAgent.sh /usr/bin/uninstallAgent.sh
    ln -s $installPath/bin/startAgent.sh /usr/bin/startAgent.sh
    ln -s $installPath/bin/stopAgent.sh /usr/bin/stopAgent.sh

    echo "" >> $installPath/wrapper/conf/parameter_file.conf
    echo "$import_key $repo $download_prefix" >> $installPath/wrapper/conf/parameter_file.conf
    out "Agent unpacked to $installPath"
    out "starting Agent..."
    bash $installPath/bin/Agent.sh installstart
    bash $installPath/bin/Agent.sh status >/dev/null 2>&1
    if [ $? -eq 0 ];then
        out "Install success!"
    else
        out "Install success,but fail to start!"
        if [ -f "$installPath/conf/.error" ];then
            cat $installPath/conf/.error
        fi
    fi
}


validateInputParameters
exitIfImported
downloadGateway
checkAndInstallDepPkgs
installAgent